package com.br4mmie.asciistory.ui;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import com.br4mmie.asciistory.CharImage;
import com.br4mmie.asciistory.Keybindings;


public class TextWindow extends Window {
	/**
	 * TexWindow Class, will be able to create a window with text in it.
	 * It will be used when the Player wants to talk to an NPC 
	 * or when something has to be explained to the Player.
	 * 
	 * First it will draw the Window
	 * Secondly it will load an text from a specific file 
	 * and split the text into characters, so the text can be printed character for character.
	 * 
	 * When the text reaches the Window's limit of containing characters, 
	 * the text will scroll, in order to show the following lines of characters
	 */
	private ArrayList<String> paragraphs;
	private int currentParagraph;
	private int currentChar;
	private int margin;
	protected int cutoff;
	protected boolean finished;
	private boolean isScrolling;
	protected boolean showContinueMessage;
	
	public TextWindow(int x, int y, int w, int h, int theMargin, boolean scrolls)
	{
		super(x, y, w, h);
		canBeClosed = true;
		currentParagraph = 0;
		currentChar = 0;
		paragraphs = new ArrayList<String>();
		isScrolling = scrolls;
		margin = theMargin;
		
		cutoff = 0;
	}
	

	/**
	 * addParaghaph() adds an paragraph to the list of paragraphs.
	 * Each paragraph contains a specific text, which will be loaded from a textfile.
	 * 
	 */
	public void addParagraph(String txt)
	{
		paragraphs.add(txt);
	}
	
	/**
	 * close() closes the active TextWindow (uses the close() method in Window)
	 */
	public void close()
	{
		super.close();
	}
	
	/**
	 * draw(CharImage target) draws the final text into the boundaries of the Window, 
	 * using the draw() method in the Window Class.
	 * Before doing so, this method will pick an desired paragraph 
	 * in the list of paragraphs.
	 * It will chop the paragraph into separate characters.
	 * with toList(), this method will create sentences out of the separate characters 
	 * and knows when to start a new line.
	 * After this, this method will print the text into the TextWindow.
	 */
	public void draw(CharImage target)
	{
		if(isClosed)return;
		clear();
		if(paragraphs.isEmpty())return;
				
		ArrayList<String> stringlist = new ArrayList<String>();
		toList(getCurrentText(), stringlist);
		if(stringlist.isEmpty()){System.out.println("lege lijst");return;}
		
		toImage(stringlist).draw(image, 1+margin, 1+margin);
		
		super.draw(target);
	}
	protected void superdraw(CharImage target)
	{
		super.draw(target);
	}
	
	/**
	 * getCurrentText()creates a String out of a paragraph from the list of paragraphs
	 */
	private String getCurrentText()
	{
		String tempString = "";
		for(int i = 0; i < currentParagraph; i++)
		{
			tempString += paragraphs.get(i)+"\n"; 
		}
		
		for(int i = 0; i <= currentChar; i++)
		{
			tempString += paragraphs.get(currentParagraph).charAt(i);
		}
		return tempString;
	}
	
	/**
	 * toList() creates sentences from the visibleText
	 * according to the width of the TextWindow (including margins).
	 * When the visibleText contains a "\n", toList() will fill up the remaining width
	 * with spaces, causing to draw the next sentence on a new line.
	 * Afterwards, this sentence will be stored in an ArrayList for sentences (sList) 
	 * and clears the current sentence to make a new one
	 */
	private void toList(String visibleText, ArrayList<String> sList)
	{
		String sentence = "";
		int textwidth = width-(margin*2)-cutoff;
				
		for(int i = 0; i < visibleText.length(); i++)
		{
			
			if((visibleText.charAt(i)=='\n')||(visibleText.charAt(i)=='~'))
			{
				while(sentence.length() < textwidth)
				{
					sentence += " ";
				}
				
			}
			else sentence += visibleText.charAt(i);
			if((sentence.length() != 0) && (sentence.length() % textwidth == 0))
			{
				String s = new String();
				s = sentence;
				sList.add(s);
				sentence = "";
				
			}
		}
		
		while(sentence.length() < textwidth)
		{
			sentence += " ";
		}
		String s = new String();
		s = sentence;
		sList.add(s);
		sentence = "";
	}
	
	/**
	 * toImage() fills the TextWindow with "spaces" 
	 * for every line that can be filled with a sentence.
	 * After doing so, it will draw the text of the whole paragraph
	 * into the TextWindow.
	 */
	private CharImage toImage(ArrayList<String> stringlist)
	{
		int textwidth = width-(margin*2)-cutoff;
		int textheight = height-(margin*2);
		
		CharImage tempImage = new CharImage(textwidth, textheight);
		tempImage.fill(' ');
				
		int tempval = textheight;
		if(stringlist.size() < textheight) tempval = stringlist.size();
			
		for(int i = 0; i < tempval; i++)
		{
			for(int j = 0; j < textwidth; j++)
			{
				tempImage.putChar(stringlist.get((stringlist.size()-1)-i).charAt(j), j, (textheight-1)-i);	
			}
		}
		
		return tempImage;
	}
	
	/** 
	 * checks if the input-key equals an enter
	 * before drawing new sentences
	 */
	public void getKeyInput()
	{
		if(!paragraphs.isEmpty())
		{
			if(Keybindings.INTERACT.pressed())currentChar = paragraphs.get(currentParagraph).length()-3;
			
		}	
	}
	
	/**
	 * lets the TextWindow scroll the text
	 */
	public void onLoop()
	{
		super.onLoop();
		if(paragraphs.isEmpty())return;
		
		finished = true;
		if(!isScrolling)
		{
			currentChar = paragraphs.get(currentParagraph).length()-1;
		}
		else
		{
			if(currentChar == paragraphs.get(currentParagraph).length()-2)
			{
				showContinueMessage = true;
			}
			if(currentChar == paragraphs.get(currentParagraph).length()-1)
			{
				if(currentParagraph < paragraphs.size()-1)
				{
					waitForEnter();
					finished = false;
					currentParagraph++;
					currentChar = 0;
					
					if (currentParagraph > paragraphs.size()-1) currentParagraph = paragraphs.size()-1;
				}
			}
			else
			{
				finished = false;
				currentChar++;
			}
		}
	
		
	}
	
	/**
	 * handles events according to the input of an key
	 */
	public void handleEvents()
	{
		super.handleEvents();
		getKeyInput();
	}
	
	/**
	 * loadFile() loads an text-file 
	 * and converts the content of the text-file into a String.
	 */
	public void loadFile(String file)
	{
		BufferedReader reader;
		String line = "";
		String text = "";
		
		try{
			reader = new BufferedReader(new FileReader(file));
			while((line = reader.readLine())!= null){
				text += (line + '\n');
			}
		}
		catch(FileNotFoundException e)
		{
			System.out.println("TextWindow error: File :" + file + " not found");
		}
		catch(IOException e)
		{
			System.out.println("TextWindow error: error opening or closing file: "+ file);
			e.printStackTrace();
		}
		int lastpos = 0;
		for(int i = 0; i < text.length(); i++)
		{
			if(text.charAt(i) == '~')
			{
				addParagraph(text.substring(lastpos, i-1));
				lastpos = i+1;
			}
		}
		addParagraph(text.substring(lastpos, text.length()-1));
	}
	

	

}

